const Router = require('@koa/router')
const mongoose = require('mongoose')

const Project = mongoose.model('Project')

const router = new Router({
    prefix: '/project',
})
/**新增项目 */
router.post('/updateandadd', async (ctx) => {
    let {
        _id,
        projectName,
        pcusId, //客户id
        pcusName,
        industry,
        projectInfo,
        price,
        endDate,
        projectState,
    } = ctx.request.body
    const one = await Project.findOne({
        _id,
    })
    if (one) {
        //更新操作
        one.projectName = projectName
        one.pcusId = pcusId
        one.pcusName = pcusName
        one.industry = industry
        one.projectInfo = projectInfo
        one.price = price
        one.endDate = endDate
        one.projectState = projectState
        const res = await one.save()
        ctx.body = {
            data: res,
            msg: '更新成功',
            code: 200
        }
    } else {
        //添加操作
        if (pcusId == "") {
            ctx.body = {
                data: null,
                code: 0,
                msg: '客户id必有',
            }
            return
        }
        const project = new Project({
            projectName,
            pcusId,
            pcusName,
            industry,
            projectInfo,
            price,
            endDate,
            projectState,
        })
        const res = await project.save()
        ctx.body = {
            data: res,
            code: 200,
            msg: '新增项目成功'
        }
    }
})

/**获取项目列表 */
router.get('/list', async (ctx) => {
    let {
        page,
        size,
        keyword
    } = ctx.query
    page = Number(page)
    size = Number(size)
    let reg = new RegExp(keyword, "gim")
    const list = await Project
        .find({ "projectName": { $regex: reg } })
        .sort({ _id: -1 }) //-1倒序
        .skip((page - 1) * size)
        .limit(size).exec()

    const total = await Project.countDocuments().exec()
    ctx.body = {
        msg: '获取项目列表成功',
        data: {
            list,
            page,
            size,
            total
        },
        code: 200
    }
})
/**删除 */
router.delete('/:id', async (ctx) => {
    const {
        id
    } = ctx.params
    const res = await Project.deleteOne({
        _id: id
    })
    ctx.body = {
        code: 200,
        msg: '删除成功',
        data: res
    }
})

/**公司业务数据接口 */
router.get('/companybusinesslist', async (ctx) => {
    const list = await Project
        .find()
        .sort({ _id: -1 }) //-1倒序
        .exec()

    const total = await Project.countDocuments().exec()
    const newList = list.map((item) => {
        return Object.assign({}, { "projectName": item.projectName, "industry": item.industry, "projectInfo": item.projectInfo })
    })

    ctx.body = {
        msg: '获取项目列表成功',
        data: {
            newList,
            total
        },
        code: 200
    }
})


module.exports = router